import os
os.environ['DISABLE_ARGUMENTS_CHECKER'] = "Yes"

from nextt.group.group_trades_portfolio import GroupFutureTrades, update_cfg

from rqalpha.apis import *
import pandas as pd


# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
    # 设置全局计数器
    context.counter = 0
    context.gt = GroupFutureTrades('1657792516@DESKTOP-U5O30PO')
    context.u = context.gt.get_universe_by_date(context.now.date())
    subscribe(list(context.u))

# before_trading此函数会在每天交易开始前被调用，当天只会被调用一次
def before_trading(context):
    # 样例商品期货在回测区间内有夜盘交易,所以在每日开盘前将计数器清零
    print(context.now)
    context.counter = 0
    context.trades_open = context.gt.get_open_trades_by_date(context.now.date())
    context.trades_close = context.gt.get_close_trades_by_date(context.now.date())
    u = context.gt.get_universe_by_date(context.now.date())
    if u != context.u:
        context.u = u
        subscribe(list(u))


# 你选择的期货数据更新将会触发此段逻辑，例如日线或分钟线更新
def handle_bar(context, bar_dict):

    # 获取当前一对合约的仓位情况。如尚未有仓位,则对应持仓量都为0
    if context.trades_open is None and context.trades_close is None:
        return

    #
    if context.trades_close is not None and context.now in context.trades_close:
        trades = context.trades_close[context.now]
        for idx,row in trades.iterrows():
            if row['side'] == 'BUY':
                buy_close(row.order_book_id, 1)
            else:
                sell_close(row.order_book_id, 1)
    #
    if context.trades_open is not None and context.now in context.trades_open:
        trades = context.trades_open[context.now]
        for idx,row in trades.iterrows():
            if row['side'] == 'BUY':
                buy_open(row.order_book_id, 1)
            else:
                sell_open(row.order_book_id, 1)



__config__ = {
  "base": {
    "start_date": "2012-01-01",
    "end_date": "2021-12-31",
    "frequency": "1m",
    "accounts": {
        "future": 10000000
    }
  },
  "extra": {
    "log_level": "error",
  },
  "mod": {
    "sys_analyser": {
      "benchmark": "000300.XSHG",
      "enabled": True,
      "plot": True
    }
  }
}


def run_gft(param={}):
    # 可让外部调用回测函数
    cfg = update_cfg(__config__, param)
    #
    start = time.time()
    print(cfg)
    ret = run_func(init=init, before_trading=before_trading, handle_bar=handle_bar, config=cfg)
    print(ret)
    print(time.time() - start)
    return ret



if __name__ == '__main__':
    import time
    from rqalpha import run_func
    # 您可以指定您要传递的参数
    # import cProfile
    # pr = cProfile.Profile()
    # pr.enable()
    run_gft()
    # pr.disable()
    # pr.print_stats('cumtime')